package com.cosfly.sharemusic.user.service.impl;

import com.cosfly.sharemusic.common.BaseUtil;
import com.cosfly.sharemusic.constant.SystemConstant;
import com.cosfly.sharemusic.entity.Result;
import com.cosfly.sharemusic.user.dao.CUserMapper;
import com.cosfly.sharemusic.user.dao.UserLoginMapper;
import com.cosfly.sharemusic.user.dto.LoginDto;
import com.cosfly.sharemusic.user.dto.PasswordDto;
import com.cosfly.sharemusic.user.dto.UserDto;
import com.cosfly.sharemusic.user.dto.UserResult;
import com.cosfly.sharemusic.user.pojo.CUser;
import com.cosfly.sharemusic.user.pojo.UserLogin;
import com.cosfly.sharemusic.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private CUserMapper userMapper;   //用户表mapper
    @Autowired
    private UserLoginMapper loginMapper;   //用户登录表mapper

    @Override
    public Result register(UserDto userDto) {
        Result result = new Result();
        Integer count = userMapper.selectByPhone(userDto.getUser_phone());   //根据手机号判断用户是否已注册
        if(count > 0){   //如果大于0，说明手机号已注册
            result.setSuccess(false);
            result.setMsg("当前手机号已注册，请换手机号注册登录");
            return result;
        }
        count = userMapper.selectByName(userDto.getUser_name());   //判断用户昵称是否重复
        if(count > 0){   //如果大于0，说明昵称重复
            result.setSuccess(false);
            result.setMsg("当前昵称已存在，请更换昵称");
            return result;
        }
        count = userMapper.selectByEmail(userDto.getUser_email());   //判断用户邮箱是否已注册
        if(count > 0){   //如果大于0，说明手机号已注册
            result.setSuccess(false);
            result.setMsg("当前邮箱已注册，请换邮箱注册登录");
            return result;
        }
        CUser user = new CUser();
        Long maxId = userMapper.selectMaxId();   //获取最大的用户Id
        if(maxId == null){
            maxId = 1l;
        }else{
            maxId = maxId ++;   //自增加1
        }
        String userCode = String.format("%010d", maxId);   //根据用户ID生成十位用户编号
        user.setUser_code(userCode);
        user.setUser_name(userDto.getUser_name());
        String passwordMd5 = null;
        try {
            passwordMd5 = BaseUtil.md5Encode(userDto.getPassword());   //密码生成32位MD5值
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("MD5加密出错，请重试。");
        }
        if(passwordMd5.equals(null)){
            return result;
        }
        user.setPassword(passwordMd5);
        user.setUser_phone(userDto.getUser_phone());
        if(!userDto.getUser_email().equals("")){
            user.setUser_email(userDto.getUser_email());
        }
        user.setUser_image("image/photo/0000000000.jpg");   //头像给默认初始头像路径
        user.setUser_type(1);
        user.setIs_del(0);
        user.setInsert_time(new Date());
        user.setUpdate_time(new Date());
        userMapper.insert(user);
        result.setSuccess(true);
        result.setMsg("注册成功，注册用户ID为:"+user.getUser_id());
        return result;
    }

    @Override
    public Result addImage(String userCode, String userImage) {
        Result result = new Result();
        CUser user = userMapper.selectByCode(userCode);   //根据用户编号获取用户信息
        String imageName = user.getUser_image().substring(user.getUser_image().lastIndexOf("/")+1);   //获取未修改前头像的图片名称
        if(imageName.equals("0000000000.jpg")){   //判断当前用户头像是否是默认头像，是默认头像不删除原头像，直接修改头像图片路径
            user.setUser_image("image/photo/"+userCode+".jpg");
            userMapper.updateimageByUserId(user);   //更新用户的头像图片路径
        }
        if(imageName.equals(userCode+".jpg")){   //判断当前用户头像图片名称与用户编号一样，一样说明有修改头像，需要删除头像图片在保存新头像图片文件
            BaseUtil.deleteDir(imageName);
        }
        String imagePath = "image/photo/"+userCode+".jpg";
        Boolean ble = BaseUtil.GenerateImage(userImage,imagePath);
        if(ble == false){
            result.setSuccess(false);
            result.setMsg("图片保存失败");
            return result;
        }
        result.setSuccess(true);
        result.setMsg("头像修改成功");
        return result;
    }

    @Override
    public UserResult login(LoginDto loginDto) {
        UserResult result = new UserResult();
        CUser user = new CUser();
        switch (loginDto.getLoginType()){
            case SystemConstant.LOGIN_TYPE:   //普通登录
                Boolean flag = BaseUtil.checkEmail(loginDto.getLoginName());   //判断登录是否是邮箱
                if (flag == true){
                    user = userMapper.selectUserByEmail(loginDto.getLoginName());   //根据邮箱获取用户信息
                    if(user== null) {
                        result.setSuccess(false);
                        result.setMsg("邮箱未注册，请注册后再登录");
                        return result;
                    }
                }
                Boolean flag1 = BaseUtil.isMobileNO(loginDto.getLoginName());   //判断登录是否是手机号
                if(flag1 == true){
                    user = userMapper.selectUserByPhone(loginDto.getLoginName());   //根据手机号获取用户信息
                    if(user== null) {
                        result.setSuccess(false);
                        result.setMsg("手机号未注册，请注册后再登录");
                        return result;
                    }
                }
                if(flag == false && flag1 == false){   //不是邮箱和手机号登录默认为昵称登录
                    user = userMapper.selectUserByName(loginDto.getLoginName());   //根据用户昵称获取用户信息
                    if(user== null) {
                        result.setSuccess(false);
                        result.setMsg("手机号未注册，请注册后再登录");
                        return result;
                    }
                }
                if(user.getIs_del() == 1){   //判断用户是否注销
                    result.setSuccess(false);
                    result.setMsg("账号已注销，请换号登录");
                    return result;
                }
                try{
                    String password = BaseUtil.md5Encode(loginDto.getPassword());
                    if(!password.equals(user.getPassword())){
                        result.setSuccess(false);
                        result.setMsg("密码错误，请输入正确密码");
                        return result;
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }
                UserDto userDto = new UserDto();
                userDto.setUser_name(user.getUser_name());
                userDto.setUser_code(user.getUser_code());
                userDto.setUser_phone(user.getUser_phone());
                userDto.setUser_email(user.getUser_email());
                userDto.setUser_image(user.getUser_image());
                userDto.setUser_type(user.getUser_type());
                result.setUserDto(userDto);   //返回用户登录信息
                break;
            case SystemConstant.WEIXIN_LOGIN_TYPE:   //微信登录
                //todo
                break;
            case SystemConstant.QQ_LOGIN_TYPE:   //qq登录
                //todo
                break;
            case SystemConstant.WEIBO_LOGIN_TYPE:   //微博登录
                //todo
                break;
            default:
                break;
        }
        UserLogin login = new UserLogin();   //将登录用户信息记录到用户登录表中保存
        login.setUser_code(user.getUser_code());
        login.setUser_phone(user.getUser_phone());
        login.setLogin_type(0);
        login.setIn_time(new Date());
        login.setIn_address("");   //添加登录地址
        loginMapper.insert(login);   //登录用户信息记录

        result.setSuccess(true);
        result.setMsg("OK");
        return result;
    }

    /**
     * 用户修改密码
     *
     * @param passDto
     * @return
     */
    @Override
    public Result modifyPassword(PasswordDto passDto) {
        Result result = new Result();
        if(!passDto.getNewPassword().equals(passDto.getNewPassword1())){
           result.setSuccess(false);
           result.setMsg("新密码不一致，请重新输入");
           return result;
        }
        String passwordMd5 = null;
        try {
            passwordMd5 = BaseUtil.md5Encode(passDto.getNewPassword());   //密码生成32位MD5值
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("MD5加密出错，请重试。");
            return result;
        }
        CUser user = userMapper.selectByCode(passDto.getUserCode());   //根据用户编号获取用户信息
        user.setPassword(passwordMd5);
        userMapper.updateByPrimaryKey(user);
        result.setSuccess(true);
        result.setMsg("OK");
        return result;
    }

    /**
     * 用户登出
     *
     * @param userCode
     * @return
     */
    @Override
    public Result out(String userCode) {
        Result result = new Result();
        CUser user = userMapper.selectByCode(userCode);   //根据用户编号获取用户信息
        UserLogin login = new UserLogin();   //将用户登出信息记录到用户登录表中保存
        login.setUser_code(user.getUser_code());
        login.setUser_phone(user.getUser_phone());
        login.setLogin_type(0);
        login.setOut_time(new Date());
        login.setIn_address("");   //添加登录地址
        loginMapper.insert(login);   //登录用户信息记录
        result.setSuccess(true);
        result.setMsg("OK");
        return result;
    }

    /**
     * 用户注销
     *
     * @param userCode
     * @return
     */
    @Override
    public Result logOut(String userCode) {
        Result result = new Result();
        CUser user = userMapper.selectByCode(userCode);   //根据用户编号获取用户信息
        user.setIs_del(1);
        user.setUpdate_time(new Date());
        userMapper.updateByPrimaryKey(user);
        result.setSuccess(true);
        result.setMsg("OK");
        return result;
    }

}
